<template>
  <audio ref="audioRef" :src="audioSrc" @ended="handleEnded" @error="handleError" />
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { ElMessage } from 'element-plus'

  const props = defineProps({
    audioSrc: {
      type: String,
      required: true,
    },
  })
  const play = ref(false)
  const audioSrc = ref(props.audioSrc)

  const audioRef = ref<HTMLAudioElement | null>(null)
  const callback = ref<Function | undefined>(undefined)

  // 播放音频
  const playAudio = () => {
    return new Promise((resolve, reject) => {
      if (audioRef.value) {
        audioRef.value.play()
          .then(() => {
            console.log('歌曲开始播放')
            play.value = true
            resolve(1)
          })
          .catch(error => {
            ElMessage.error('当前歌曲播放失败')
            reject(error)
          })
      }
    })
  }

  // 暂停音频
  const pauseAudio = () => {
    if (audioRef.value) {
      audioRef.value.pause()
      play.value = false
    }
  }

  // 音频播放结束
  const handleEnded = (fun:Function) => {
    if (play.value && callback.value) {
      play.value = false
      callback.value()
    } else callback.value = fun
  }

  // 错误处理
  const handleError = () => {
    play.value = false
    if (audioRef.value) {
      audioRef.value.currentTime = 0
    }
    ElMessage.error('出错了 请重新搜索播放歌曲')
  }

  // 切换歌曲
  const handoffMusic = async (musicUrl: string) => {
    pauseAudio() // 先暂停当前音频
    audioSrc.value = musicUrl // 更新音频源
    setTimeout(async () => {
      await playAudio()
    }, 500)
  }

  // 获取当前歌曲进度
  const getCurrentTime = (): number => {
    if (audioRef.value) {
      return audioRef.value.currentTime
    }
    return 0
  }

  // 获取歌曲总时长
  const getDuration = (): number => {
    if (audioRef.value && play.value) {
      return audioRef.value.duration
    }
    return 0
  }

  // 修改当前歌曲进度
  const setCurrentTime = (time: number) => {
    if (audioRef.value && time >= 0 && time <= audioRef.value.duration) {
      audioRef.value.currentTime = time
    }
  }

  // 暴露方法
  defineExpose({
    playAudio,
    pauseAudio,
    handleEnded,
    handoffMusic,
    getCurrentTime,
    getDuration,
    setCurrentTime,
  })
</script>

<style scoped lang="scss">
/* Add any styles if needed */
</style>
